package com.third.customer.site.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.third.customer.model.data.JsonResult;
import com.third.customer.model.data.UserType;
import com.third.customer.model.tables.Area;
import com.third.customer.service.AreaService;
import com.third.customer.service.data.AreaReq;
import com.third.customer.service.utils.PageResult;
import com.third.customer.site.UserInfo;
import com.third.customer.site.controller.resp.AreaResp;
import com.third.customer.site.support.ThirdAuth;
import com.third.customer.site.support.ThirdUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by hehuaichun on 2020/5/22.
 */
@RestController
@RequestMapping("/areas")
public class AreaCtrl {

    @Autowired
    private AreaService areaService;

    @GetMapping
    @ThirdAuth(UserType.ORDINARY)
    public JsonResult list(@ThirdUser UserInfo userInfo, AreaReq req) {
        Page<Area> page = areaService.list(req.toParam(userInfo.getCompanyId()));
        List<AreaResp> resps = page.getRecords().stream().map(AreaResp::convert).collect(Collectors.toList());
        return JsonResult.ok(PageResult.build(page, resps));
    }

    @GetMapping("/{id}")
    @ThirdAuth(UserType.ORDINARY)
    public JsonResult getById(@ThirdUser UserInfo userInfo,
                              @PathVariable Long id) {
        return JsonResult.ok(AreaResp.convert(areaService.getById(userInfo.getCompanyId(), id)));
    }

    @PostMapping
    @ThirdAuth(UserType.ORDINARY)
    public JsonResult create(@ThirdUser UserInfo userInfo,
                             @Valid AreaReq req) {
        req.validateForEdit();
        return JsonResult.ok(AreaResp.convert(areaService.create(userInfo.getCompanyId(), req)));
    }

    @PostMapping("/{id}/modify")
    @ThirdAuth(UserType.ORDINARY)
    public JsonResult modify(@ThirdUser UserInfo userInfo,
                             @PathVariable Long id,
                             @Valid AreaReq req) {
        return JsonResult.ok(AreaResp.convert(areaService.modify(userInfo.getCompanyId(), id, req)));
    }

    @PostMapping("/{id}/delete")
    @ThirdAuth(UserType.ORDINARY)
    public JsonResult delete(@ThirdUser UserInfo userInfo, @PathVariable Long id) {
        return JsonResult.ok(areaService.delete(userInfo.getCompanyId(), id));
    }
}
